<?php


namespace App\Http\Controllers;


use App\Handlers\OtherHandler;
use App\Models\User;
use App\Models\UserFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Laravel\Socialite\Facades\Socialite;

class SocialController extends MainController {


    public function redirectToProvider( $type ) {
        return Socialite::driver( $type )->redirect();
    }


    /**
     * Obtain the user information from Google.
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function handleProviderCallback( $type ) {
        return $this->socialCheck( $type );
    }

    private function socialCheck( $type ) {
        try {
            $user = Socialite::driver( $type )->stateless()->user();
        } catch ( \Exception $e ) {
            return redirect( '/login' );
        }
        $existingUser = User::where(
            function($query) use ($user,$type){
                if($user->email){
                    $query->orWhere('email', 'LIKE', $user->email);
                }
                $query->orWhere($this->driverTitleToTableTitle( $type ),$user->id);
                return $query;
            })->first();
        if ( ! auth()->check() ) {
            if ( $existingUser && $existingUser->{$this->driverTitleToTableTitle( $type )} != null ) {
                auth()->login( $existingUser, true );
            } elseif ( $existingUser && $existingUser->{$this->driverTitleToTableTitle( $type )} == null ) {
                $existingUser->{$this->driverTitleToTableTitle($type)} = $user->id;
                $existingUser->active = true;
                $existingUser->save();
                auth()->login($existingUser, true);
            }else{
                $newUser = new User;
                $newUser->name = $newUser->page_title = $user->name;
                $newUser->email = $user->email;
//                if ($user->avatar) {
//                    $newUser->photo_id = UserFile::saveRemoteFile($user->avatar);
//                }
                $newUser->{$this->driverTitleToTableTitle($type)} = $user->id;
                $newUser->active = true;
                if($newUser->makeSave()) {
                    auth()->login($newUser, true);
                }
            }
            session( [ 'social_name' => $type ] );
        } else {
            try {
                $newUser = User::find(auth()->user()->id);
                $newUser->{$this->driverTitleToTableTitle($type)} = $user->id;
                $newUser->active = true;
                $newUser->save();
                auth()->login( $newUser, true );
                session( [ 'social_name' => $type ] );
                return Redirect::to( "settings#password" );
            } catch ( \Exception $e ) {
                return Redirect::to( "settings#password" )->withErrors( [ 'msg' => 'Пользователь уже существует' ] );
            }
        }

        return OtherHandler::urlBack();
    }

    private function driverTitleToTableTitle( $type ) {
        switch ( $type ) {
            case "vkontakte":
                return "vk";
            case "facebook":
                return "fb";
            default:
                return $type;
        }
    }

}
